#!/usr/bin/env python
import sys, math, random
import src.crop as cr
from mpi4py import MPI
import numpy as np
import operator as op
import util

comm = MPI.COMM_WORLD
p = comm.size
rank = comm.rank
root = 0

step = 1
done = False
result = ""
while not done :
	if rank % 2 ** step != 0:
			send_msg = {"msg": chr(97+rank), "step": step}
			_dest = rank - 2 ** (step - 1)
			data = comm.send(send_msg, dest=_dest)
			print rank, "sending to ", _dest
			done = True
	else :
		_source = rank + 2 ** (step - 1)
		recv_msg = comm.recv(source=_source)
#		print rank, "recv from %s at step %s: %s" % (_source, str(step), recv_msg["msg"])
		step = int(recv_msg["step"]) + 1
		result += recv_msg["msg"]
		if step <= math.log(p, 2):
			if rank != root :
				_dest = rank - 2 ** (step - 1)
				send_msg = {"msg": "".join([result,chr(97+rank)]) , "step": step}
				print rank, "sending to ", _dest
				data = comm.send(send_msg, dest=_dest)
		else :
			done = True
print "Rank %s. \tData: %s" % (rank, sorted(list(chr(97+rank) + result)))



